<template>
  <view class="container">
    <!-- 轮播图 -->
    <uni-swiper-dot :info="info" :current="current" field="content" :mode="mode">
      <swiper class="swiper-box" @change="change" circular autoplay>
        <swiper-item v-for="(item, index) in info" :key="index">
          <image :src="item.src" class="swiper-image" mode="scaleToFill" style="width: 100%;"></image>
        </swiper-item>
      </swiper>
    </uni-swiper-dot>

    <!-- 功能列表 -->
    <uni-section title="功能列表" type="line" style="margin-bottom: 10px;">
      <view class="icon-content">
        <view class="icon-item icon-item-count3 ohl-no-padding-top" @click="openPage('/pages/depositrecords/depositrecords')">
          <uni-icons type="download" color="#007aff" :size="26" />
          <text class="uni-mt-5 uni-subtitle">我要存胎</text>
        </view>
        <view class="icon-item icon-item-count3 ohl-no-padding-top" @click="openPage('/pages/releaserecords/releaserecords')">
          <uni-icons type="upload" color="#007aff" :size="26" />
          <text class="uni-mt-5 uni-subtitle">我要取胎</text>
        </view>
        <view class="icon-item icon-item-count3 ohl-no-padding-top icon-item-count-wrapper">
          <!-- 包裹容器，用于定位红点 -->
          <view @click="openPage('/pages/expirationrecords/expirationrecords')">
            <!-- uni-icons 图标 -->
            <uni-icons type="notification" color="#007aff" :size="26" />

            <!-- 小红点 -->
            <view class="red-dot" v-if="hasNewNotifications"></view>
          </view>
          <text class="uni-mt-5 uni-subtitle">到期</text>
        </view>

      </view>
    </uni-section>

    <!-- 库存信息 -->
    <uni-section title="库存信息" type="line" style="margin-bottom: 10px;">
      <view class="icon-content">
        <view class="icon-item icon-item-count2 ohl-no-padding-top">
          <text class="uni-mt-5 uni-subtitle ohl-no-margin-top">在存套数</text>
          <text class="uni-mt-5 uni-subtitle" style="color: #5e6d82">{{indexPageTotalQuantity.invoiceQuantity}} 套</text>
        </view>
        <view class="icon-item icon-item-count2 ohl-no-padding-top">
          <text class="uni-mt-5 uni-subtitle ohl-no-margin-top">在存个数</text>
          <text class="uni-mt-5 uni-subtitle" style="color: #5e6d82">{{indexPageTotalQuantity.remainingQuantity}} 个</text>
        </view>
      </view>
    </uni-section>

    <!-- 预约记录 -->
    <uni-section title="预约记录" type="line">
      <view style="padding: 0px 20px">
        <uni-segmented-control
          :current="tabIndex"
          :values="['存胎记录', '取胎记录']"
          @clickItem="onClickItem"
          styleType="button"
          activeColor="#007aff"
        ></uni-segmented-control>

        <view class="content">
          <!-- 存胎记录 Tab -->
          <view v-show="tabIndex === 0" style="margin: 10px 0;">
            <uni-table border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th align="center">车牌号</uni-th>
                <uni-th align="center">店铺名称</uni-th>
                <uni-th align="center">状态</uni-th>
                <uni-th align="left">预约时间</uni-th>
                <uni-th align="left">到期时间</uni-th>
              </uni-tr>
              <uni-tr v-for="item in depositRecordsList" :key="item.id">
                <uni-td align="center" v-if="`${item.status}` !== '6'">
                  <text class="link-text" @tap="openDepositrecordsDetail(item.id, 'update')">
                    {{ item.licensePlate }}
                  </text>
                </uni-td>
                <uni-td align="center" v-if="`${item.status}` === '6'">
                  <text class="link-text" @tap="openExpirationrecordsDetail(item.id, 'update')">
                    {{ item.licensePlate }}
                  </text>
                </uni-td>
                <uni-td align="center">{{ findById(item.storeId,selectData.storeList)?.storeName }}</uni-td>
                <uni-td align="center">
                  <uni-tag :text="getCodeText(item.status,selectData.depositRecordsStatusList)" :type="getTagType(item.status)" size="mini"/>
                </uni-td>
                <uni-td align="left">{{ formatDate(item.startDate) }}</uni-td>
                <uni-td align="left">{{ formatDate(item.expirationDate) }}</uni-td>
              </uni-tr>
            </uni-table>
          </view>

          <!-- 取胎记录 Tab -->
          <view v-show="tabIndex === 1">
            <uni-table border stripe emptyText="暂无更多数据" style="margin: 10px 0;">
              <uni-tr>
                <uni-th align="center">车牌号</uni-th>
                <uni-th align="center">店铺名称</uni-th>
                <uni-th align="center">状态</uni-th>
                <uni-th align="left">创建时间</uni-th>
              </uni-tr>
              <uni-tr v-for="item in releaseRecordsList" :key="item.id">
                <uni-td align="center">
                  <text class="link-text" @tap="openReleaserecordsDetail(item.id, 'update')">
                    {{ item.licensePlate }}
                  </text>
                </uni-td>
                <uni-td align="center">{{ findById(item.storeId,selectData.storeList)?.storeName }}</uni-td>
                <uni-td align="center">
                  <uni-tag :text="getCodeText(item.status,selectData.releaseRecordsStatusList)" :type="getTagType(item.status)" size="mini"/>
                </uni-td>
                <uni-td align="left">{{ formatDate(item.createTime) }}</uni-td>
              </uni-tr>
            </uni-table>
          </view>

          <view style="width: 100%;height: 200px">
            &nbsp;
            &nbsp;
            &nbsp;
            &nbsp;
          </view>
        </view>
      </view>
    </uni-section>
  </view>
</template>

<script lang="ts">
  import { DepositRecordsApi, DepositRecordsVO } from '@/sheep/api/depositrecords';
  import { ReleaseRecordsApi, ReleaseRecordsVO } from '@/sheep/api/releaserecords';
  import { DictUtils } from '@/sheep/store/DictUtils';
  import { StoreApi } from '@/sheep/api/store';

  export default {
    data() {
      return {
        selectData:{
          depositRecordsStatusList:[],
          releaseRecordsStatusList:[],
          storageTypeList:[],
          storeList:[]
        },
        info: [
          { src: '/static/lunbo2.jpg', content: '内容 A' },
          { src: '/static/lunbo1.jpg', content: '内容 B' }
        ],
        current: 0,
        mode: 'round',
        tabIndex: 0,
        depositRecordsList: [] as DepositRecordsVO[], // 存储记录声明为 DepositRecordsVO 数组类型
        releaseRecordsList: [] as ReleaseRecordsVO[],  // 其他列表，您可以根据实际情况更新类型
        indexPageTotalQuantity:{
          invoiceQuantity: 0 ,
          remainingQuantity: 0,
        },
        hasNewNotifications: false,
        storeId:uni.getStorageSync('storeId')
      };
    },
    onLoad: function (options) {
      this.initSelectData();
    },
    onShow() {
      uni.startPullDownRefresh();
    },
    onPullDownRefresh() {
      this.getDepositRecordsList();
      this.getReleaseRecordsList();
      this.getIndexPageTotalQuantity();
      this.getHasNewNotifications();
      setTimeout(function () {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    methods: {
      openExpirationrecordsDetail(id: string,type: string = "create") {
        // 初始化一个参数对象，id 必须存在
        const params = { type };

        // 如果 id 为空，则不执行跳转
        if (!(!id || id === 'null' || id === 'undefined')) {
          params.id = id
        }

        // 构建查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        // 跳转到目标页面
        uni.navigateTo({
          url: `/pages/expirationrecords/expirationrecordsDetail?${queryString}`
        });
      },
      // 点击 FAB 按钮时跳转到详情页
      openDepositrecordsDetail(id: string,type: string = "create") {
        // 初始化一个参数对象，id 必须存在
        const params = { type };

        // 如果 id 为空，则不执行跳转
        if (!(!id || id === 'null' || id === 'undefined')) {
          params.id = id
        }

        // 构建查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        // 跳转到目标页面
        uni.navigateTo({
          url: `/pages/depositrecords/depositrecordsDetail?${queryString}`
        });
      },
      // 点击 FAB 按钮时跳转到详情页
      openReleaserecordsDetail(id: string,type: string = "create") {
        // 初始化一个参数对象，id 必须存在
        const params = { type };

        // 如果 id 为空，则不执行跳转
        if (!(!id || id === 'null' || id === 'undefined')) {
          params.id = id
        }

        // 构建查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        // 跳转到目标页面
        uni.navigateTo({
          url: `/pages/releaserecords/releaserecordsDetail?${queryString}`
        });
      },
      change(e: any) {
        this.current = e.detail.current;
      },
      onClickItem(e: any) {
        this.tabIndex = e.currentIndex;
        if(this.tabIndex === 0){
          this.getDepositRecordsList();
        }else{
          this.getReleaseRecordsList();
        }
      },
      openPage(url: string) {
        uni.navigateTo({
          url: url
        });
      },
      async getHasNewNotifications() {
        try {
          //查询是否有到期的存单
          const {data:findByStatus6Data} = await DepositRecordsApi.getDepositRecordsPage({storeId:this.storeId,status:6});
          this.hasNewNotifications = !!findByStatus6Data?.list?.length;
        } catch (error) {
          console.error('Failed to fetch deposit records1:', error);
        }
      },
      async getDepositRecordsList() {
        try {
          const {data} = await DepositRecordsApi.getDepositRecordsPage({storeId:this.storeId,status:[0,1,2,3],pageSize:100});
          this.depositRecordsList = data.list;
        } catch (error) {
          console.error('请求错误1:', error);
        }
      },
      async getIndexPageTotalQuantity() {
        try {
          const {data} = await DepositRecordsApi.getIndexPageTotalQuantity({storeId:this.storeId,status:[0,1,2,3,4,6]});
          this.indexPageTotalQuantity = data;
        } catch (error) {
          console.error('请求错误2:', error);
        }
      },
      async getReleaseRecordsList() {
        try {
          const {data}  = await ReleaseRecordsApi.getReleaseRecordsPage({storeId:this.storeId,pageSize:100});
          this.releaseRecordsList = data.list;
        } catch (error) {
          console.error('请求错误3:', error);
        }
      },
      // 格式化时间
      formatDate(date: string) {
        const d = new Date(date);
        return d.toLocaleString(); // 使用本地化字符串格式化时间
      },
      getCodeText(status: string,codeList:[]) {
        const item = codeList.find(item=>item.value==status);
        return item?.label || '未知';
      },
      findById(id: string,list:[]):any {
        const item = list.find(item=>item.id==id);
        return item;
      },
      async initSelectData() {
        this.selectData.releaseRecordsStatusList = DictUtils.getDictData('tire_release_records_status');
        this.selectData.depositRecordsStatusList = DictUtils.getDictData('tire_deposit_records_status');

        this.selectData.storageTypeList = DictUtils.getDictData('tire_storage_type');

        const storeResult = await StoreApi.getStorePage({});
        this.selectData.storeList = storeResult?.data?.list || [];
      },
      getTagType(status: number){
        switch (status) {
          case 1:return "primary";
          case 2:return "success";
          case 3:return "warning";
          case 4:return "error";
          default:return "";
        }
      },
    }
  };
</script>

<style lang="scss">
  .icon-item-count-wrapper {
    position: relative; /* 使包裹容器为相对定位 */
  }

  .red-dot {
    position: absolute;
    top:0;
    right: 35px;
    width: 8px;
    height: 8px;
    background-color: red;
    border-radius: 50%;
    border: 2px solid white; /* 红点的边框，增强对比 */
  }

  .link-text {
    color: blue; /* 设为蓝色 */
    text-decoration: underline; /* 添加下划线 */
  }
  .icon-content {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: center;

    .icon-item {
      display: flex;
      box-sizing: border-box;
      align-items: center;
      padding: 10px;
      text-align: center;
      flex-direction: column;

      &-count2 {
        width: calc(100% / 2);
      }

      &-count3 {
        width: calc(100% / 3);
      }

      .ohl-no-padding-top {
        padding-top: 0;
      }

      .ohl-no-margin-top {
        margin-top: 0;
      }
    }
  }
</style>
